<template>
	<view>
		<u-toast ref="uToast" />
		<common :tips='commonTips'></common>
		<u-action-sheet @click="clickLongpressAction" :list="longPressActionList"
			v-model="longPressActionShow"></u-action-sheet>
		<view class="search-box">
			<u-search bg-color="#ffffff" @search="search()" v-model="keywords" class="search-box-u-search"
				shape="square" placeholder="搜索其实很简单" :clearabled="true" :show-action="false"></u-search>
			<view @click="search(false)" v-if="showSearchRes" class="search-button">取消</view>
			<view @click="search(true)" v-else class="search-button">搜索</view>
		</view>
		<view v-if="!showSearchRes" class="group-chat-users">
			<navigator :url="'/pages/center/info?id=' + user.id" v-for="(user, userIdx) in leader" :key="userIdx"
				class="user-item">
				<image class="user-avatar" :src="user.avatar"></image>
				<view class="user-info"><u-tag class="leader-tag" text="群主" size="mini" shape="circle"
						type="warning" />{{user.nickname ? user.nickname_origin + '(' + user.nickname + ')':user.nickname_origin}}
				</view>
				<!-- <u-button v-if="!user.is_friend" @click.stop="addFriend(user.id)" size="mini" class="user-button">加好友</u-button> -->
			</navigator>
			<u-index-list :scrollTop="scrollTop" :indexList="indexList">
				<view v-for="(item, index) in indexList" :key="index">
					<u-index-anchor :index="item" />
					<!-- @longpress="longpressUser(user.id, user.nickname ? user.nickname_origin + '(' + user.nickname + ')':user.nickname_origin)" :url="'/pages/center/info?id=' + user.id" -->
					<navigator v-for="(user, userIdx) in users[item]" :key="userIdx" class="user-item">
						<image class="user-avatar" :src="user.avatar"></image>
						<view class="user-info">
							<u-tag
								v-if="user.is_admin == 1"
								class="leader-tag"
								text="管理员"
								size="mini"
								shape="circle"
								type="primary"
							/>
							{{user.nickname ? user.nickname_origin + '(' + user.nickname + ')' : user.nickname_origin}}
						</view>
						<!-- @click.stop="addFriend(user.id)" -->
						<!-- 						<u-button v-if="!user.is_friend"  size="mini" class="user-button">加好友</u-button> -->
						<u-button
							v-if="leader.length && currentUserId === leader[0].id"
							size="mini"
							class="user-button"
							@click.stop="toggleAdmin(user)"
						>
							{{ user.is_admin == 1 ? '取消管理员' : '设为管理员' }}
						</u-button>
					</navigator>
				</view>
			</u-index-list>
		</view>
		<view v-if="showSearchRes" class="search-res">
			<!-- @longpress="longpressUser(user.id, user.nickname ? user.nickname_origin + '(' + user.nickname + ')':user.nickname_origin)" :url="'/pages/center/info?id=' + user.id" -->
			<navigator v-for="(user, userIdx) in groupChatMember" :key="userIdx" class="user-item">
				<image class="user-avatar" :src="user.avatar"></image>
				<view class="user-info">
					<u-tag
						v-if="user.is_admin == 1"
						class="leader-tag"
						text="管理员"
						size="mini"
						shape="circle"
						type="primary"
					/>
					{{user.nickname ? user.nickname_origin + '(' + user.nickname + ')' : user.nickname_origin}}
				</view>
				<!-- @click.stop="addFriend(user.id)" -->
				<!-- // <u-button v-if="!user.is_friend" size="mini" class="user-button">加好友</u-button> -->
				<u-button
					v-if="leader.length && currentUserId === leader[0].id"
					size="mini"
					class="user-button"
					@click.stop="toggleAdmin(user)"
				>
					{{ user.is_admin == 1 ? '取消管理员' : '设为管理员' }}
				</u-button>
			</navigator>
			<view v-if="!groupChatMember.length" class="im-data-none">没有搜索结果~</view>
		</view>
	</view>
</template>

<script>
	import Config from "@/common/config.js"; // 本地配置数据
	export default {
		data() {
			return {
				id: 0,
				keywords: '',
				scrollTop: 0,
				indexList: [],
				users: [],
				leader: [],
				showSearchRes: false,
				groupChatMember: [],
				longPressActionID: 0,
				longPressActionShow: false,
				longPressActionList: [],
				commonTips: '',
				currentUserId: 0 // 当前登录用户 ID
			}
		},
		watch: {
			users: {
				handler(newVal) {
					// 当 users 有值（不为空对象）时再调用
					if (Object.keys(newVal).length > 0) {
						this.getGroupUserStatus();
					}
				},
				// deep: true, // 深度监听，确保内部数组变化也能触发
				immediate: true // 如果你希望初始化时就触发可以设置为 true
			},
		},
		onLoad: function(query) {
			this.id = query.id ? query.id : 0
			const userinfo = uni.getStorageSync('userinfo');
			this.currentUserId = userinfo.id;
			this.ws.pageFun(this.pageDataLoad, this);
		},
		onShow() {
			this.ws.checkNetwork(this)
		},
		onPullDownRefresh: function() {
			this.ws.pageFun(this.pageDataLoad(true), this);
			this.ws.onMessageCallBack.set('group_chat_member', (msg) => {
				if (parseInt(msg.data.data.id) == parseInt(this.id) && msg.data.data.refresh) {
					this.$refs.uToast.show({
						title: '刷新成功~',
						type: 'success'
					})
					uni.stopPullDownRefresh()
					// ✅ 打印 indexList 值
					console.log('group_chat_member 回调中的 users:', this.users)
				}
			})
		},
		methods: {
			pageDataLoad: function(refresh = false) {
				  console.log(JSON.stringify(this.users, null, 2)); // 美化输出
				var that = this;
				that.ws.send({
					c: 'Message',
					a: 'groupChatMember',
					data: {
						'id': this.id,
						'method': 'get',
						'lettersort': 'lettersort',
						'refresh': refresh
					},
					success(res) {
						// 假设 res.data 是用户分组后的数据对象
						that.users = res.data.users || [];
						that.leader = res.data.leader || [];
						that.indexList = Object.keys(that.users);
					}
				});
			},
			getGroupUserStatus() {
				const userinfo = uni.getStorageSync('userinfo');
				const userToken = userinfo.token;
				this.$u.post(`https://${Config.baseUrl}/api/Group_operate/getGroupUsers?im_tourists_token=${userToken}`, {
					group_id: this.id,
				}).then(res => {
					console.log("444res:" + res)
					if (res.status === 'success') {
						const statusList = res.data;
						const statusMap = {};
						statusList.forEach(item => {
							statusMap[item.user_id] = item;
						});
						// 更新 users 的状态
						for (const key in this.users) {
							this.users[key] = this.users[key].map(user => {
								if (statusMap[user.id]) {
									user.is_admin = statusMap[user.id].is_admin;
									user.is_muted = statusMap[user.id].is_muted;
								}
								return user;
							});
						}
			
						// 更新搜索结果成员状态（如果需要）
						this.groupChatMember = this.groupChatMember.map(user => {
							if (statusMap[user.id]) {
								user.is_admin = statusMap[user.id].is_admin;
								user.is_muted = statusMap[user.id].is_muted;
							}
							return user;
						});
			
						console.log(JSON.stringify(this.users, null, 2)); // 美化输出
					} else {
						this.$refs.uToast?.show({
							title: res.message || '获取成员状态失败',
							type: 'error'
						});
					}
				}).catch(err => {
					console.error("getGroupUserStatus 请求失败", err);
					this.$refs.uToast?.show({
						title: '网络异常',
						type: 'error'
					});
				});
			},

			onPageScroll(e) {
				this.scrollTop = e.scrollTop;
			},
			search: function(show = true) {
				var that = this
				if (!show) {
					that.groupChatMember = []
					that.showSearchRes = false
					return;
				}
				if (!that.keywords) {
					that.$refs.uToast.show({
						title: '请输入关键词~',
						type: 'error'
					})
					return;
				}
				that.ws.pageFun(function() {
					that.ws.send({
						c: 'Message',
						a: 'groupChatMember',
						data: {
							'id': that.id,
							'method': 'get',
							'keywords': that.keywords
						}
					})
				}, that)
				this.getGroupUserStatus();
			},
			addFriend: function(id) {
				uni.navigateTo({
					url: '/pages/search/add-contact?type=user&id=' + id
				})
			},
			longpressUser: function(id, username) {
				this.longPressActionID = id
				this.longPressActionShow = true
				this.longPressActionList = [{
					text: '删除成员',
					color: '#f74c31',
					subText: username
				}]
			},
			clickLongpressAction: function(index) {
				var that = this
				if (index == 0) {
					that.ws.pageFun(function() {
						that.ws.pageRefresh.chatSetting = true
						that.ws.pageRefresh.sessionInfo = true
						that.ws.send({
							c: 'Message',
							a: 'delGroupMember',
							data: {
								'id': that.id,
								'member_id': that.longPressActionID
							}
						})
					}, that)
				}
			},
			toggleAdmin(user) {
				const userinfo = uni.getStorageSync('userinfo');
				const userToken = userinfo.token;
			
				const newStatus = user.is_admin === 1 ? 0 : 1;
			
				this.$u.post(`https://${Config.baseUrl}/api/Group_operate/setGroupAdmin?im_tourists_token=${userToken}`, {
					group_id: this.id,
					user_id: user.id,
					is_admin: newStatus
				}).then(res => {
					if (res.status === 'success') {
						// 更新本地用户状态
						user.is_admin = newStatus;
						this.$refs.uToast?.show({
							title: res.message,
							type: 'success'
						});
						this.getGroupUserStatus();
					} else {
						this.$refs.uToast?.show({
							title: res.message || '操作失败',
							type: 'error'
						});
					}
				}).catch(err => {
					console.error("设置管理员失败", err);
					this.$refs.uToast?.show({
						title: '网络错误',
						type: 'error'
					});
				});
			}

		}
	}
</script>

<style>
	page {
		background: #F8F8F8;
	}

	.search-box {
		display: flex;
		align-items: center;
		padding: 20rpx 4vw;
	}

	.search-box .search-box-u-search {
		flex: 1;
	}

	.search-button {
		padding-left: 30rpx;
	}

	.user-item {
		display: flex;
		align-items: center;
		background: #FFFFFF;
		height: 100rpx;
		padding: 20rpx;
	}

	.user-avatar {
		height: 90rpx;
		width: 90rpx;
		margin-right: 20rpx;
		border-radius: 16rpx;
	}

	.user-info {
		display: flex;
		font-size: 30rpx;
		width: 62%;
		overflow: hidden;
	}

	.leader-tag {
		margin-right: 10rpx;
	}

	.user-button {
		margin-left: auto;
		margin-right: 30rpx;
	}
</style>